package com.magicsoft.weitown.fragment;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.boyuan.huijiaoyu.AboutWeiTownActivity;
import com.boyuan.huijiaoyu.AccountLoginActivity;
import com.boyuan.huijiaoyu.DownloadManagerActivity;
import com.boyuan.huijiaoyu.InviteRegisterActivity;
import com.boyuan.huijiaoyu.LogoutActivity;
import com.boyuan.huijiaoyu.MainActivity;
import com.boyuan.huijiaoyu.PersonSettingActivity;
import com.boyuan.huijiaoyu.PersonalMessageActivity;
import com.boyuan.huijiaoyu.R;
import com.easemob.EMCallBack;
import com.easemob.chat.EMChatManager;
import com.example.huanxin.DemoApplication;
import com.magicsoft.app.helper.SharePreferenceHelper;
import com.magicsoft.app.helper.ToastHelper;
import com.magicsoft.app.helper.UpdateVersionHelper;
import com.magicsoft.app.wcf.listener.PostRecordResponseListener;
import com.magicsoft.constant.Constant;
import com.magicsoft.weitown.ui.CustomDialog;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.download.BaseImageDownloader;
import com.ttcaca.cas.android.client.model.User;
import com.zxing.decoding.FinishListener;

public class HomePersonalFragment extends BaseFragment implements
		OnClickListener {

	private final static String TAG = "HomePersonalFragment";

	private final static int MESSAGE_INTENT = 1;
	// 头像
	private ImageView iv_icon;
	// 姓名
	private TextView tv_name;
	// 职位
	private TextView tv_job;
	private DisplayImageOptions options;
	private User account;// 登录账户
	private RelativeLayout rl_personal_message;// 个人信息
	// 我的下载
	private RelativeLayout rl_downloaded;
	// 邀请
	private RelativeLayout rl_invative;
	// 设置
	private RelativeLayout rl_setting;
	// 退出登录
	private RelativeLayout rl_logout;

	private MyInfoChangeReceive myInfoChangeReceive;
	private MyFirstChangeHeadIcon firstChangeHeadIconreceiver;

	String realname;
	String address;
	String mail;
	String mobile;

	private SharedPreferences sp;

	private String education;

	private String idCardNo;

	private String sex;

	private String accountId;

	private String yonghu;

	private MyNameChangeReceive myNamereceive;

	private TextView tv_title;

	private String id;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.home_personal_fragment,
				container, false);
		SharedPreferences sp1 = getActivity().getSharedPreferences("a.xml",
				0);
		yonghu = sp1.getString("username", "");
		prepareView(view);
		prepareData();
		registerNameReceiver();
		registerMyReceiver();
		registerLoginReceiver();
		return view;
	}

	private void registerLoginReceiver() {
		firstChangeHeadIconreceiver = new MyFirstChangeHeadIcon();
		IntentFilter filter = new IntentFilter();
		filter.addAction(Constant.FirstChangePersonHeadIcon);
		getActivity().registerReceiver(firstChangeHeadIconreceiver, filter);
	}

	class MyFirstChangeHeadIcon extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			accountId = sp.getString("accountId", "");
			String job = sp.getString("familyname", "");
			mobile = sp.getString("username", "");
			realname = sp.getString("realname", "");
			mail = sp.getString("mail", "");
			address = sp.getString("address", "");
			education = sp.getString("education", "");
			idCardNo = sp.getString("idCardNo", "");
			sex = sp.getString("sex", "");
			tv_name.setText(realname);
			tv_job.setText(job);
		}
	}

	//异步加载图片
	class ImageAsyncTask extends AsyncTask<String, Void, Bitmap>{
		
		ImageView image;
		public ImageAsyncTask(ImageView image){
			this.image = image;
		}

		@Override
		protected Bitmap doInBackground(String... params) {
			Bitmap bitmap = null;
			String path = params[0];
			try {
				URL url = new URL(path);
				URLConnection openConnection = url.openConnection();
				InputStream inputStream = openConnection.getInputStream();
				bitmap = BitmapFactory.decodeStream(inputStream);
				FileOutputStream fos = new FileOutputStream(path);
				bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
			} catch (MalformedURLException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return bitmap;
		}
		
		@Override
		protected void onPostExecute(Bitmap result) {
			iv_icon.setImageBitmap(result);
			super.onPostExecute(result);
		}
		
	}
	
	private void DownloadHeadIcon() {
		String uri = Constant.photourl + id;
		imageLoader.displayImage(uri, iv_icon, options);
		ImageAsyncTask imageAsyncTask = new ImageAsyncTask(iv_icon);
		imageAsyncTask.execute(uri);
	}

	private void registerMyReceiver() {
		myInfoChangeReceive = new MyInfoChangeReceive();
		IntentFilter filter = new IntentFilter();
		filter.addAction(Constant.ChangePersonHeadIcon);
		getActivity().registerReceiver(myInfoChangeReceive, filter);
	}

	class MyInfoChangeReceive extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			String filePath = intent.getStringExtra("filePath");
			SharePreferenceHelper.setHeadIconUri(filePath, getActivity());
			BaseImageDownloader imageDownloader = new BaseImageDownloader(
					getActivity());
			try {
				InputStream is = imageDownloader.getStream(filePath, null);
				Bitmap bitmap = BitmapFactory.decodeStream(is);
				iv_icon.setImageBitmap(bitmap);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

	}

	private void registerNameReceiver() {
		myNamereceive = new MyNameChangeReceive();
		IntentFilter filter = new IntentFilter();
		filter.addAction("name_action");
		getActivity().registerReceiver(myNamereceive, filter);
	}

	public class MyNameChangeReceive extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			realname = intent.getStringExtra("name1");
			tv_name.setText(realname);
		}

	}

	private void prepareView(View view) {
		// 头像
		iv_icon = (ImageView) view.findViewById(R.id.iv_icon);
		iv_icon.setOnClickListener(this);
		// 姓名
		tv_name = (TextView) view.findViewById(R.id.tv_name_person);
		tv_title = (TextView) view.findViewById(R.id.mytitle);
		tv_job = (TextView) view.findViewById(R.id.tv_job);
		rl_personal_message = (RelativeLayout) view
				.findViewById(R.id.rl_personal_message);
		rl_personal_message.setOnClickListener(this);
		options = new DisplayImageOptions.Builder()
				.showImageOnLoading(R.drawable.default_header)
				.showImageForEmptyUri(R.drawable.default_header)
				.showImageOnFail(R.drawable.default_header).cacheInMemory(true)
				.cacheOnDisc(true).considerExifParams(true)
				// .displayer(new RoundedBitmapDisplayer(20))
				.build();

		// 我的下载
		rl_downloaded = (RelativeLayout) view.findViewById(R.id.rl_downloaded);
		rl_downloaded.setOnClickListener(this);

		// 邀请
		rl_invative = (RelativeLayout) view.findViewById(R.id.rl_invative);
		rl_invative.setOnClickListener(this);
		// 设置
		rl_setting = (RelativeLayout) view.findViewById(R.id.rl_setting);
		rl_setting.setOnClickListener(this);
		// 退出登录
		rl_logout = (RelativeLayout) view.findViewById(R.id.rl_logout);
		rl_logout.setOnClickListener(this);

	}

	public void prepareData() {

		sp = getActivity().getSharedPreferences("a.xml", 0);
		accountId = sp.getString("accountId", "");
		String job = sp.getString("familyname", "");
		mobile = sp.getString("username", "");
		realname = sp.getString("realname", "");
		mail = sp.getString("mail", "");
		address = sp.getString("address", "");
		education = sp.getString("education", "");
		idCardNo = sp.getString("idCardNo", "");
		sex = sp.getString("sex", "");
		id = sp.getString("id", "");
		tv_name.setText(realname);
		tv_job.setText(job);
		DownloadHeadIcon();
	}

	@Override
	public void onClick(View v) {

		switch (v.getId()) {
		case R.id.rl_personal_message:
			// 信息修改
			Intent messageIntent = new Intent(getActivity(),
					PersonalMessageActivity.class);
			messageIntent.putExtra("yonghu", yonghu);
			messageIntent.putExtra("accountId", accountId);
			messageIntent.putExtra("mobile", mobile);
			messageIntent.putExtra("realname", realname);
			messageIntent.putExtra("mail", mail);
			messageIntent.putExtra("address", address);
			messageIntent.putExtra("education", education);
			messageIntent.putExtra("idCardNo", idCardNo);
			messageIntent.putExtra("sex", sex);
			messageIntent.putExtra("id", id);
			messageIntent.putExtra("backtitle", tv_title.getText().toString().trim());
			startActivityForResult(messageIntent, MESSAGE_INTENT);

			break;

		case R.id.rl_downloaded:
			// 邀请
			Intent doorIntent = new Intent(getActivity(), InviteRegisterActivity.class);
			doorIntent.putExtra("backtitle", tv_title.getText().toString().trim());
			startActivity(doorIntent);
			break;

		case R.id.rl_invative:
			// 我的下载
			Intent downloadIntent = new Intent(getActivity(), DownloadManagerActivity.class);
			downloadIntent.putExtra("backtitle", tv_title.getText().toString().trim());
			startActivity(downloadIntent);
			break;
		case R.id.rl_setting:
			// 设置
			Intent intent = new Intent(getActivity(), PersonSettingActivity.class);
			intent.putExtra("backtitle", tv_title.getText().toString().trim());
			startActivity(intent);
			break;

		case R.id.iv_icon:
			// if (account != null &&
			// StringUtils.isImageUrl(account.getIconurl())) {
			// Intent imageIntent = new Intent(getActivity(),
			// ImageViewZoomActivity.class);
			//
			// imageIntent.putExtra("imageurl", account.getIconurl());
			// startActivity(imageIntent);
			// }

			break;
		case R.id.rl_logout:
			// 退出
//			logout();
			Intent intent2 = new Intent(getActivity(), LogoutActivity.class);
			startActivityForResult(intent2, 0);
			break;
		// 服务条款
		// case R.id.rl_police:
		// Intent policeIntent = new Intent(getActivity(),
		// SettingPolicyActivity.class);
		// startActivity(policeIntent);
		//
		// break;

		default:
			break;
		}

	}
	

	/**
	 * 手动升级检查
	 */
	public void checkNewVersion() {

		showLoading(getResources().getString(R.string.check_new_version));// 检测新版本...
		new UpdateVersionHelper(getActivity())
				.checkUpdate(new PostRecordResponseListener() {

					@Override
					public void onFinish(String succString) {
						hideLoading();

					}

					@Override
					public void onFailed(String failString) {
						hideLoading();
						ToastHelper.showMsg(getActivity(), getResources()
								.getString(R.string.present_new_version), true);

					}
				});
	}

	/**
	 * 退出应用
	 */
	private void logout() {

		final CustomDialog dialog = new CustomDialog(getActivity(),
				R.style.qr_dialog);
		dialog.show();
		// 标题
		TextView tv_title = (TextView) dialog.findViewById(R.id.dialog_title);
		tv_title.setText("确定退出");
		// 内容
		TextView tv_content = (TextView) dialog
				.findViewById(R.id.dialog_content);
		tv_content.setVisibility(View.INVISIBLE);
		tv_content.setText("");
		// 右上角取消
		ImageView imag_cancel = (ImageView) dialog
				.findViewById(R.id.dialog_img_cancel);
		imag_cancel.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				dialog.cancel();
			}
		});
		// 确定按钮
		Button btn_ok = (Button) dialog.findViewById(R.id.dialog_button_ok);
		btn_ok.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {

				dialog.cancel();
				SharedPreferences sp3 = getActivity().getSharedPreferences(
						"user.xml", 0);
				Editor edit = sp3.edit();
				edit.putBoolean("islogin", false);
				edit.commit();
				EMChatManager.getInstance().logout();
				((MainActivity) getActivity()).popupLogin();
			}
		});
		// 取消按钮
		Button btn_cancel = (Button) dialog
				.findViewById(R.id.dialog_button_cancel);
		btn_cancel.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				dialog.cancel();
			}
		});
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		getActivity().unregisterReceiver(myInfoChangeReceive);
		getActivity().unregisterReceiver(firstChangeHeadIconreceiver);
		getActivity().unregisterReceiver(myNamereceive);
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == MESSAGE_INTENT) {
			if (resultCode == Activity.RESULT_OK) {
				prepareData();
			}
		}else if(requestCode == 0 && resultCode == 1){
			MainActivity main = (MainActivity) getActivity();
			main.closeActivity();
		}else if(requestCode == 0 && resultCode == 2){
			MainActivity main = (MainActivity) getActivity();
			main.closeActivity();
		}
	}

}
